<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      <el-breadcrumb-item>修改密码</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-form ref="userFormRef" :model="userForm" label-width="100px" class="userform" :rules="userFormRules">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="原密码" prop="password">
          <el-input v-model="userForm.password" type="password" ref="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="userForm.newPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPassword2">
          <el-input v-model="userForm.newPassword2" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmChange">确认修改</el-button>
          <el-button @click="cancelChange">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkPassword = (rule, value, callback) => {
      if (value !== this.userForm.newPassword) {
        return callback(new Error('两次输入密码不一致'))
      }
      callback()
    }

    return {
      userForm: {
        username: window.localStorage.getItem('username'),
        password: '',
        newPassword: '',
        newPassword2: ''
      },
      userFormRules: {
        password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        newPassword2: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {
    //  点击确认修改按钮
    confirmChange() {
      this.$refs.userFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('userinfo/changepassword/', this.userForm)
          if (res.meta.status === 200) {
            this.$message.success('密码修改成功！请使用新密码重新登录')
            window.sessionStorage.clear()
            this.$router.push('/login')
            return
          } else if (res.meta.status === 201) {
            this.$refs.password.focus()
            return this.$message.error('用户原密码验证失败')
          } else {
            return this.$message.error('用户修改密码失败，请联系管理员！')
          }
        } else {
          return false
        }
      })
    },
    //   点击取消修改按钮
    cancelChange() {
      this.$router.push('/welcome')
    }
  }
}
</script>

<style lang="less" scoped>
.userform {
  width: 500px;
}
</style>
